/** \file BendRelease.cpp
   \author belot.nicolas
	\todo Fix speed
*/

#include "BendRelease.h"

namespace libtrckr {

BendRelease::BendRelease():c(1.,1024){
	
}

BendRelease::BendRelease(const BendRelease& b):c(b.c){
	info = b.info;
}

BendRelease::~BendRelease(){

}

void BendRelease::Tune(DynArray<double> conf){
	info = DynArray<DynArray<double> >(conf.size()/3);
	//double duration, speed, ,ratio, maintain;
	double oldspeed = 1.0;
	for(uint i=0;i<conf.size()/4;i++){
		DynArray<double> d(4);
		d[0]=conf[i+0];
		d[1]= (conf[i+1] - oldspeed ) / conf[i+0];
		d[2]=conf[i+1];
		d[3]=conf[i+2];
		info[i]=d;
		oldspeed=conf[i+1];
	}
}

Buffer& BendRelease::apply(Buffer& b , int*size){
	double ratio=1.;
	//where are we?
	int i=0;
	double tmptime=0.;
	while(i<info.size() && tmptime < elapsed){
		tmptime += info[i][1] - info[i][3];
		i++;
	}
	i--;
	tmptime -=info[i][1] - info[i][3];
	
	if( elapsed - tmptime > info[i][1]){
		if(i>=1){
			ratio = info[i-1][1] + info[i][1] * (elapsed - tmptime);
		}else{
			ratio = 1.0 + info[i][1] * (elapsed - tmptime);
		}
	}else{
		ratio=info[i][2];
	}
	c.ratio(ratio);
	Buffer b2(*size);
	for(uint i=0;i<*size;i++){
		b2[i]=b[i];
	}
	int retsize=c.convert(b2,b);
	*size=retsize;
	elapsed+=*size;
	return b;
}

}
